#!/usr/bin/python
#coding:utf-8

import redis
import time
import sys
import re
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sys.path.append(BASE_DIR)

from config.tdm_config import *
from alert.app import log_warn_alert, get_jxd_dis
from alert.alert_daemon import client_send
#from alert.send_mail import sendmail

def spawn_alert_mail(r, server_online_list, server_offline_list):
    t = int(time.time()*1000)

    #报警消除
    for city, jxd, server in server_online_list:
        alert_server_key = '%s:%s:%s:%s' % (city, jxd, server, tdm_redis_key_server_online_suffix)
        if r.hexists(tdm_redis_key_server_item_alert, alert_server_key):
            print 'no alert', alert_server_key
            r.hdel(tdm_redis_key_server_item_alert, alert_server_key);

    #报警产生
    for city, jxd, server in server_offline_list:
        alert_server_key = '%s:%s:%s:%s' % (city, jxd, server, tdm_redis_key_server_online_suffix)
        alert_server_val = '%d,%d' % (t, t)
        #print alert_server_key
        #print alert_server_val

        last_alert_str = r.hget(tdm_redis_key_server_item_alert, alert_server_key)
        print 'alert', t, city, jxd, server, last_alert_str
        log_warn_alert(r, city, jxd, server, tdm_redis_key_server_online_suffix, 'server', t, \
                0, 0, {'send_email_list':'yanlong@100tal.com;shifufeng@100tal.com;xuguocan@100tal.com'})

        last_alert_t = 0
        last_mail_t = 0
        if last_alert_str:
            last_alert_t, last_mail_t = map(int, last_alert_str.split(','))
            #print last_alert_t, last_mail_t
        #更新报警时间
        alert_server_val = '%d,%d' % (t, last_mail_t)
        r.hset(tdm_redis_key_server_item_alert, alert_server_key, alert_server_val)

        if (not last_mail_t) or (t - last_mail_t > (1000 * 60 * 60 * 24)):      # out of 1 day
            #发送邮件
            if get_jxd_dis(r, city, jxd):
                print city, jxd, 'is disabled'
                return
            login = {}
            login['user'] = 'cxyf@100tal.com'
            login['passwd'] = 'icstest123'
            alert_email_config = r.hgetall(tdm_redis_key_alert)
            send_mail_allows = alert_email_config.get(tdm_redis_key_alert_items, '').split(',')

            #print login
            #print send_mail_allows

            if 'server' in send_mail_allows:
                mail_to_addr = 'qujianning@100tal.com;yanlong@100tal.com;xuguocan@100tal.com;shifufeng@100tal.com'
                mail_subject = '%s %s' % (alert_server_key, '服务器宕机告警')
                alert_time = time.strftime("%Y-%m-%d %X", time.localtime(t/1000))
                mail_content = '%s %s' % (alert_time, mail_subject)
                mail = {
                    'to_addr': mail_to_addr.split(';'),
                    'subject': mail_subject,
                    'content': mail_content,
                }

                #print login
                #print mail
                client_send(login, mail)
                #update the sendmail timestamp
                alert_server_val = '%d,%d' % (t, t)
                r.hset(tdm_redis_key_server_item_alert, alert_server_key, alert_server_val)


def get_server_list(r, item):
    server_online_list = []
    server_offline_list = []
    t = int(time.time()*1000)
    server_item_list = r.keys('%s:*:%s' % (tdm_redis_key_server_item_prefix, item))
    for server_load_name in server_item_list:
        #print server_load_name
        #server_item_北京_汇鑫城_10045-bj-phy-ics3_cpuload
        server = re.match('%s:(.*):cpuload' % tdm_redis_key_server_item_prefix, server_load_name)
        if not server:
            continue
        server_str = server.groups()[0]
        city, jxd, server = server_str.split(':')

        server_keys = r.hkeys(server_load_name)
        server_keys.sort()
        server_online_name = '%s:%s:%s:%s:%s' % (tdm_redis_key_server_item_prefix, city, jxd, server, tdm_redis_key_server_online_suffix)
        server_online_key = '%d' % (t, )

        if (time.time() - int(server_keys[-1])/1000)/(10*60) >= 1:      # out of 10 min
            server_online_val = '%d' % (-1, )
            r.hset(server_online_name, server_online_key, server_online_val)
            # the return offline server list
            server_offline_list.append((city, jxd, server))
        else:
            server_online_val = '%d' % (1, )
            r.hset(server_online_name, server_online_key, server_online_val)
            server_online_list.append((city, jxd, server))

    return server_online_list, server_offline_list

if __name__ == '__main__':
    r = redis.Redis(host='127.0.0.1', db=1)
    server_online_list, server_offline_list = get_server_list(r, 'cpuload')
    for i in server_online_list:
        print 'online', ':'.join(i)
    for i in server_offline_list:
        print 'offline', ':'.join(i)
    spawn_alert_mail(r, server_online_list, server_offline_list)
